package com.tina.listener;

import com.alibaba.fastjson.JSON;
import com.tina.constant.ShopCode;
import com.tina.entity.Flowers;
import com.tina.entity.Orders;
import com.tina.exception.CustomerException;
import com.tina.service.IFlowersService;
import com.tina.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * 支付超时处理
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.payTimeOutMsg.topic}", consumerGroup = "${mq.payTimeOutMsg.consumer.group.name}", messageModel = MessageModel.BROADCASTING)
public class PayTimeOutListener implements RocketMQListener<MessageExt> {

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IFlowersService flowersService;

    @Override
    public void onMessage(MessageExt messageExt) {
        log.info("接收到取消订单消息");
        try {
            String body = new String(messageExt.getBody(), "UTF-8");
            log.info("body->{}", body);
            Orders orders = JSON.parseObject(body, Orders.class);
            // 判断一下是否已经支付，如果没有支付就设置为取消
            ordersService.checkOrderPay(orders.getOrderId());

            // 修改订单状态
            Orders o = new Orders();
            o.setOrderId(orders.getOrderId());
            o.setStatus(ShopCode.SHOP_ORDER_CANCEL.getCode());
            ordersService.editOrders(o);

            // 回退库存
            Flowers flowersById = flowersService.selectFlowersById(orders.getFlowersId());
            Flowers flowers = new Flowers();
            flowers.setId(orders.getFlowersId());
            flowers.setStock(flowersById.getStock() + orders.getNumber());
            flowersService.editFood(flowers);

            log.info("更改订单支付状态为已取消成功");
        } catch (CustomerException | UnsupportedEncodingException e) {

            log.info("更改订单支付状态为已取消失败");
            e.printStackTrace();
        }

    }
}
